#!/usr/bin/env bash

function ohos-tool-env:try_alias()
{
    if ! which "$1" >/dev/null; then
        alias "$1=$2"
    fi
}

function ohos-tool-env:main()
{
    export PATH="$PATH:$OHOS_TOOL"

    while read line; do
        [[ "$line" =~ (/) ]] || continue
        line="$(sed "s/$(echo -e "\033")\[[^m]*m/|/g" <<< "$line")"
        local repo_name=$(cut -d'|' -f2 <<< "$line")
        local repo_path=$(cut -d'|' -f4 <<< "$line")
        export ${repo_name// /}=$repo_path
    done <<< $(ohos-tool config@repo)

    ohos-tool-env:try_alias ohf 'ohos-tool hdc@pull --file'
    ohos-tool-env:try_alias ohh 'ohos-tool hdc@hilog'
    ohos-tool-env:try_alias ohp 'ohos-tool hdc@push --file'
    ohos-tool-env:try_alias ohr 'ohos-tool hdc@rr'
    ohos-tool-env:try_alias ohs 'ohos-tool hdc@shell'
    ohos-tool-env:try_alias oht 'ohos-tool hdc@trace'

    local str
    cd $OHOS_TOOL
    while read str; do
        str="${str:11}"
        local alias_name="${str// : */}"
        local target_name="${str//* : /}"
        ohos-tool-env:try_alias "$alias_name" "ohos-tool $target_name"
    done <<< "$(find commands/ -type f | sort | xargs cat | egrep "^#alias.cmd")"
    cd - >/dev/null

    unset -f ohos-tool-env:main
    unset -f ohos-tool-env:try_alias
    bash "$OHOS_TOOL/scripts/ohos-tool-update.sh"
}

ohos-tool-env:main
